const db = require("@/db/index");
const bcrypt = require("bcryptjs");

// 分页查询员工列表
exports.queryEmployees = (req, resp) => {
  try {
    const {
      pageSize = 10,
      pageNum = 1,
      staffNo,
      staffName,
      departmentName,
      position
    } = req.body;

    // 构建查询条件
    let conditions = [];
    let params = [];

    if (staffNo) {
      conditions.push('staff_no LIKE ?');
      params.push(`%${staffNo}%`);
    }
    if (staffName) {
      conditions.push('staff_name LIKE ?');
      params.push(`%${staffName}%`);
    }
    if (departmentName) {
      conditions.push('department_name LIKE ?');
      params.push(`%${departmentName}%`);
    }
    if (position) {
      conditions.push('position LIKE ?');
      params.push(`%${position}%`);
    }

    // 组装WHERE子句
    const whereClause = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';

    // 查询总数
    const countSql = `SELECT COUNT(*) as total FROM employee ${whereClause}`;
    db.query(countSql, params, (err, totalResult) => {
      if (err) return resp.err(err);
      const total = totalResult[0].total;

      // 查询数据
      const offset = (pageNum - 1) * pageSize;
      const dataSql = `
                SELECT * FROM employee 
                ${whereClause} 
                ORDER BY create_time DESC 
                LIMIT ? OFFSET ?
            `;

      db.query(dataSql, [...params, pageSize, offset], (err, rows) => {
        if (err) return resp.err(err);

        resp.ok({
          total,
          list: rows,
          pageSize,
          pageNum
        });
      });
    });
  } catch (error) {
    resp.err(error);
  }
};

// 新增员工
exports.addEmployee = (req, resp) => {
  try {
    const employeeInfo = req.body;

    // 验证必填字段
    if (!employeeInfo.staffName) {
      return resp.err("员工姓名不能为空");
    }
    if (!employeeInfo.departmentName) {
      return resp.err("部门名称不能为空");
    }

    // 生成员工工号
    const getMaxStaffNoSql = "SELECT MAX(staff_no) as maxNo FROM employee WHERE staff_no LIKE 'X%'";
    db.query(getMaxStaffNoSql, (err, result) => {
      if (err) {
        console.error('获取最大工号失败:', err);
        return resp.err("添加员工失败: " + err.message);
      }

      // 生成新的工号
      let newStaffNo = 'X001';
      if (result[0].maxNo) {
        const currentNumber = parseInt(result[0].maxNo.substring(3));
        newStaffNo = `X${String(currentNumber + 1).padStart(3, '0')}`;
      }

      // 对密码进行加密，如果没有设置密码则使用默认密码123456
      employeeInfo.password = bcrypt.hashSync(employeeInfo.password || '123456', 10);

      // 构建插入数据，处理可选字段
      const insertData = {
        staff_no: newStaffNo,
        password: employeeInfo.password,
        staff_name: employeeInfo.staffName,
        department_name: employeeInfo.departmentName,
        position: employeeInfo.position || null,
        sex: employeeInfo.sex || null,
        age: employeeInfo.age || null,
        tel_no: employeeInfo.telNo || null,
        avator: employeeInfo.avator || null,
        base_pay: employeeInfo.basePay || null
      };

      // 插入员工数据
      const insertSql = "insert into employee set ?";
      db.query(insertSql, insertData, (err, result) => {
        if (err) {
          console.error('添加员工失败:', err);
          return resp.err("添加员工失败: " + err.message);
        }
        if (result.affectedRows !== 1) {
          return resp.err("添加员工失败!");
        }
        resp.ok({
          id: result.insertId,
          ...insertData,
          create_time: new Date()
        }, "添加员工成功");
      });
    });
  } catch (error) {
    console.error('添加员工异常:', error);
    resp.err("添加员工失败: " + error.message);
  }
};

// 删除员工
exports.deleteEmployee = (req, resp) => {
  try {
    const ids = req.body;

    // 验证必填字段
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return resp.err("员工ID列表不能为空");
    }

    // 删除员工数据
    const deleteSql = "DELETE FROM employee WHERE id IN (?)";
    db.query(deleteSql, [ids], (err, result) => {
      if (err) {
        console.error('删除员工失败:', err);
        return resp.err("删除员工失败: " + err.message);
      }
      if (result.affectedRows === 0) {
        return resp.err("未找到要删除的员工!");
      }
      resp.ok({
        deletedCount: result.affectedRows
      }, `成功删除${result.affectedRows}个员工`);
    });
  } catch (error) {
    console.error('删除员工异常:', error);
    resp.err("删除员工失败: " + error.message);
  }
};

// 修改员工信息
exports.updateEmployee = (req, resp) => {
  try {
    const employeeInfo = req.body;

    // 验证是否提供了员工ID
    if (!employeeInfo.id) {
      return resp.err("员工ID不能为空");
    }

    // 构建更新数据，只更新提供的字段
    const updateData = {};

    if (employeeInfo.staffName !== undefined) {
      updateData.staff_name = employeeInfo.staffName;
    }
    if (employeeInfo.departmentName !== undefined) {
      updateData.department_name = employeeInfo.departmentName;
    }
    if (employeeInfo.position !== undefined) {
      updateData.position = employeeInfo.position || null;
    }
    if (employeeInfo.sex !== undefined) {
      updateData.sex = employeeInfo.sex || null;
    }
    if (employeeInfo.age !== undefined) {
      updateData.age = employeeInfo.age || null;
    }
    if (employeeInfo.telNo !== undefined) {
      updateData.tel_no = employeeInfo.telNo || null;
    }
    if (employeeInfo.avator !== undefined) {
      updateData.avator = employeeInfo.avator || null;
    }
    if (employeeInfo.basePay !== undefined) {
      updateData.base_pay = employeeInfo.basePay || null;
    }

    // 如果提供了新密码，则加密后更新
    if (employeeInfo.password) {
      updateData.password = bcrypt.hashSync(employeeInfo.password, 10);
    }

    // 如果没有任何要更新的字段，直接返回
    if (Object.keys(updateData).length === 0) {
      return resp.err("未提供任何要更新的字段");
    }

    // 更新员工数据
    const updateSql = "UPDATE employee SET ? WHERE id = ?";
    db.query(updateSql, [updateData, employeeInfo.id], (err, result) => {
      if (err) {
        console.error('修改员工信息失败:', err);
        return resp.err("修改员工信息失败: " + err.message);
      }
      if (result.affectedRows === 0) {
        return resp.err("未找到该员工!");
      }

      // 查询更新后的员工信息
      const selectSql = "SELECT * FROM employee WHERE id = ?";
      db.query(selectSql, [employeeInfo.id], (err, rows) => {
        if (err) {
          console.error('查询更新后的员工信息失败:', err);
          return resp.err("查询更新后的员工信息失败: " + err.message);
        }
        if (rows.length === 0) {
          return resp.err("未找到该员工!");
        }
        // 不返回密码字段
        const updatedEmployee = rows[0];
        delete updatedEmployee.password;

        resp.ok(updatedEmployee, "修改员工信息成功");
      });
    });
  } catch (error) {
    console.error('修改员工信息异常:', error);
    resp.err("修改员工信息失败: " + error.message);
  }
}; 